<?php

App::import('Sanitize');
class UsersController extends AppController{
    var $name = 'Users';
    var $helpers = array('Html', 'Form', 'Javascript');

    var $components = array('Acl');

    function register(){

        if(!empty($this->data)){
             //if the form is submitted

            //Some sanitize
            $this->data['User']['email_addr'] = Sanitize::paranoid($this->data['User']['email_addr'], array('@', '.', '-', '+','_'));
            $this->data['User']['first_name'] = Sanitize::paranoid($this->data['User']['first_name']);
            $this->data['User']['last_name'] = Sanitize::paranoid($this->data['User']['last_name']);


                if(!empty($this->data['User']['passwd']) && !empty($this->data['User']['password'])) {
                    if ($this->data['User']['password'] != $this->data['User']['passwd']) {
                        $this->User->invalidate('pass_wrong');
                    }
                } else {
                    $this->User->invalidate('empty_pass');
                }

                $this->data['User']['passwd'] = md5($this->data['User']['passwd']);

                if($this->User->save($this->data)){
                    //controller call save method on User model

                    $this->Session->setFlash('Your registration is accepted.');

                    $result = $this->User->find('first', array('conditions'=>array('User.email_addr'=>$this->data['User']['email_addr'])));

                    $this->Session->write('account_type', 'user');

                    $this->Session->write('user',$result['User']);

                    //Moving and renaming the file uploaded
                    if($this->data['User']['image']){
                        $target_path = 'img/profile/user/'.$result['User']['id'].'.jpg';
                        move_uploaded_file($this->data['User']['image']['tmp_name'], $target_path);
                    }

                    //Creating ARO for the new user
                    $parent = $this->Acl->Aro->findByAlias('Users');
                    $aro = new Aro();
                    $aro->create();

                    $aro->save(array(
                    'alias' => $this->data['User']['email_addr'],
                    'model' => 'User',
                    'foreign_key' => $result['User']['id'],
                    'parent_id' => $parent['Aro']['id'])
                    );

                    $this->Acl->Aro->save();

                    $this->redirect(array('action'=>'index'), null, true);

                } else {
                    $this->data['User']['passwd'] = '';
                }
        }
    }

    function login(){

        if($this->data){

            $email = $this->data['User']['email_addr'];
            $pass = $this->data['User']['passwd'];

            //Some sanitize
            $pass = Sanitize::paranoid($pass,array('_'));
            $email = Sanitize::paranoid($email,array('_'),array('@', '.', '-', '+','_'));

            $result = $this->User->find('first', array('conditions'=>array('User.email_addr'=>$this->data['User']['email_addr'])));

            $this->set('result', $result);

            if($result && ($result['User']['passwd'] == md5($this->data['User']['passwd']))){

                $this->Session->write('account_type', 'user');
                $this->Session->write('user',$result['User']);
                //Delete host session variables
                //->
                //$this->redirect(array('action'=>'index'), null, true);
                $this->redirect(array('controller' => 'events', 'action'=>'index'), null, true);
            } else {
                $this->set('error', true);
            }
        }
    }

    function logout(){

        $this->Session->delete('user');
        $this->Session->delete('account_type');
        $this->redirect(array('action'=>'login'), null, true);
    }

    function index(){

        $email_addr = $this->Session->read('user');
        $email_addr = $email_addr['email_addr'];
        if($email_addr){
            $result = $this->User->find('first', array(
                'conditions'=>array('User.email_addr'=>$email_addr)
                ));
            $this->set('user', $result['User']);
        } else {
            $this->redirect(array('action'=>'login'), null, true);
        }
    }

    function edit_profile($id = null) {


        $user = $this->Session->read('user');

        $this->set('user', $user);

        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid user data.', true));
            $this->redirect(array('action' => 'edit_profile', $id));
        }

        if (!empty($this->data)) {


            if (empty($this->data['User']['passwd'])) {

                $this->Session->setFlash(__('Your password is required to change your profile.', true));
                $this->redirect(array('action' => 'edit_profile', $id));
            } else {

                if (md5($this->data['User']['passwd']) == $user['passwd']) {

                    $this->Session->setFlash($user['passwd']);

                    if (!empty($this->data['User']['password']) && !empty($this->data['User']['psword'])) {

                        if (($this->data['User']['password'] == $this->data['User']['psword'])) {

                            $this->data['User']['passwd'] = md5($this->data['User']['password']);
                        } else {

                            $this->Session->setFlash(__('The new password is not correct.', true));
                            $this->redirect(array('action' => 'edit_profile', $id));
                        }
                    } else {

                        unset($this->data['User']['passwd']);
                    }


                    if ($this->User->save($this->data)) {
                        $this->Session->setFlash(__('Your profile has been updated', true));

                        //If email changes --> Updating ACO & ARO
                        if ($user['email_addr'] != $this->data['User']['email_addr']) {

                            $aro = $this->Acl->Aro->findByAlias($user['email_addr']);

                            $aro_id = $aro['Aro']['id'];

                            $query = 'update aros set alias = \'' . $this->data['User']['email_addr'] . '\' where id = ' . $aro_id;

                            $this->User->query($query);

                            $aco = $this->Acl->Aco->findByAlias($user['email_addr']);

                            $aco_id = $aco['Aco']['id'];

                            $query = 'update acos set alias = \'' . $this->data['User']['email_addr'] . '\' where id = ' . $aco_id;

                            $this->User->query($query);
                        }

                        //Moving and renaming the file uploaded
                        if ($this->data['User']['image']) {
                            $target_path = 'img/profile/user/' . $id . '.jpg';
                            move_uploaded_file($this->data['User']['image']['tmp_name'], $target_path);
                        }

                        //Updating user session variable
                        $this->Session->delete('user');

                        $user = $this->User->read(null, $id);

                        $this->Session->write('user', $user['User']);
                    } else {
                        $this->Session->setFlash(__('Your profile could not be saved. Please, try again.', true));
                    }

                    $this->redirect(array('action' => 'edit_profile', $id));
                } else {

                    $this->Session->setFlash(__('Old password is not correct.', true));
                    $this->redirect(array('action' => 'edit_profile', $id));
                }
            }
        }

        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
            $this->data['User']['passwd'] = '';
        }
    }

    /*
    $search_where = array('category'=>'misc');

    $return_these_db_columns = 'id,title,content,publish_date';

    $order_by = 'publish_date DESC';

    $show_this_page = 2; //this is only static for testing - would be dynamic for pagination

    $show_this_many_per_page = 15; //number of blog posts to show per page



    * only Blogs with thier "category" column matching "misc" are returned

    * this will return an array of Blog objects with variables id, title, content, and publish_date

    * the array will be ordered by publish_date from biggest to smallest

    * only results 16-30 from the database will be returned



    $blogs =

    $this->Blog->findAll(

        $search_where,

        $return_these_database_columns,

        $order_by,

        $show_this_many_per_page,

        $show_this_page

    );
         */
}

?>
